#!/bin/bash

# SPAM3UK 快速启动脚本
# 用于生产环境的一键启动和状态检查

set -e

echo "🚀 SPAM3UK 生产环境启动脚本"
echo "================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查是否在正确目录
if [[ ! -f "spam3uk" ]]; then
    echo -e "${RED}❌ 错误: 未找到spam3uk可执行文件${NC}"
    echo "请确保在 /data/prod/spam3uk 目录下运行此脚本"
    exit 1
fi

# 检查配置文件
if [[ ! -f "spam4uk-config.prod.json" ]]; then
    echo -e "${YELLOW}⚠️  警告: 未找到生产配置文件${NC}"
    if [[ -f "spam3uk-config.json" ]]; then
        echo "使用默认配置文件..."
    else
        echo -e "${RED}❌ 错误: 未找到配置文件${NC}"
        exit 1
    fi
fi

echo "1. 检查当前服务状态..."
if systemctl is-active --quiet spam3uk; then
    echo -e "${GREEN}✅ 服务已运行${NC}"
    echo "当前状态:"
    sudo systemctl status spam3uk --no-pager -l
    
    echo -e "\n选择操作:"
    echo "1) 重启服务"
    echo "2) 停止服务" 
    echo "3) 查看日志"
    echo "4) 测试API"
    echo "5) 退出"
    
    read -p "请选择 (1-5): " choice
    
    case $choice in
        1)
            echo "重启服务..."
            sudo systemctl restart spam3uk
            echo -e "${GREEN}✅ 服务已重启${NC}"
            ;;
        2)
            echo "停止服务..."
            sudo systemctl stop spam3uk
            echo -e "${YELLOW}⚠️  服务已停止${NC}"
            exit 0
            ;;
        3)
            echo "查看实时日志 (Ctrl+C退出):"
            sudo journalctl -u spam3uk -f
            ;;
        4)
            # 继续到测试部分
            ;;
        5)
            exit 0
            ;;
        *)
            echo "无效选择，继续测试..."
            ;;
    esac
else
    echo -e "${YELLOW}⚠️  服务未运行，正在启动...${NC}"
    
    # 启动服务
    echo "2. 启动SPAM3UK服务..."
    sudo systemctl start spam3uk
    
    # 等待启动
    echo "等待服务启动..."
    sleep 3
    
    # 检查启动状态
    if systemctl is-active --quiet spam3uk; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
    else
        echo -e "${RED}❌ 服务启动失败${NC}"
        echo "查看错误日志:"
        sudo journalctl -u spam3uk --no-pager -l
        exit 1
    fi
    
    # 设置开机自启
    echo "3. 设置开机自启..."
    sudo systemctl enable spam3uk
    echo -e "${GREEN}✅ 已设置开机自启${NC}"
fi

echo -e "\n4. 检查端口监听..."
if netstat -tlnp 2>/dev/null | grep -q :5700; then
    echo -e "${GREEN}✅ 端口5700正在监听${NC}"
    netstat -tlnp | grep :5700
else
    echo -e "${RED}❌ 端口5700未监听${NC}"
    echo "检查服务状态:"
    sudo systemctl status spam3uk --no-pager
    exit 1
fi

echo -e "\n5. 测试API接口..."

# 健康检查
echo "测试健康检查..."
if curl -s http://localhost:5700/health > /dev/null; then
    echo -e "${GREEN}✅ 健康检查通过${NC}"
    curl -s http://localhost:5700/health | jq '.' 2>/dev/null || curl -s http://localhost:5700/health
else
    echo -e "${RED}❌ 健康检查失败${NC}"
    exit 1
fi

echo -e "\n测试车辆API..."
if curl -s http://localhost:5700/api/vehicles?page=1&page_size=1 > /dev/null; then
    echo -e "${GREEN}✅ 车辆API响应正常${NC}"
    echo "车辆数据示例:"
    curl -s http://localhost:5700/api/vehicles?page=1&page_size=1 | jq '.[0] | {id, make, model, vehicle_type}' 2>/dev/null || curl -s http://localhost:5700/api/vehicles?page=1&page_size=1 | head -3
else
    echo -e "${YELLOW}⚠️  车辆API可能无数据或响应异常${NC}"
fi

echo -e "\n6. 数据库连接测试..."
if mysql -u root -p123 -e "USE dcp-cloud; SELECT COUNT(*) as vehicle_count FROM make_info_uk;" 2>/dev/null; then
    echo -e "${GREEN}✅ 数据库连接正常${NC}"
    echo "数据统计:"
    mysql -u root -p123 -e "USE dcp-cloud; 
    SELECT COUNT(*) as vehicle_count FROM make_info_uk;
    SELECT COUNT(*) as trim_count FROM trim_info_uk;" 2>/dev/null
else
    echo -e "${YELLOW}⚠️  数据库连接需要手动验证${NC}"
fi

echo -e "\n${GREEN}🎉 SPAM3UK启动完成！${NC}"
echo "================================"
echo "✅ 服务状态: 运行中"
echo "✅ 访问地址: http://118.145.200.164:5700"
echo "✅ API文档: http://118.145.200.164:5700/api/vehicles"
echo "✅ 健康检查: http://118.145.200.164:5700/health"
echo ""
echo "🔧 管理命令:"
echo "   查看状态: sudo systemctl status spam3uk"
echo "   重启服务: sudo systemctl restart spam3uk"
echo "   查看日志: sudo journalctl -u spam3uk -f"
echo "   回滚版本: ./rollback.sh"
echo ""
echo "📊 监控建议:"
echo "   - 定期检查 /health 端点"
echo "   - 监控服务日志异常"
echo "   - 检查磁盘和内存使用"

# 提供快速测试选项
echo -e "\n是否执行完整API测试? (y/n): "
read -t 10 test_choice
if [[ "$test_choice" == "y" || "$test_choice" == "Y" ]]; then
    echo -e "\n执行完整API测试..."
    
    echo "📋 分类统计:"
    curl -s http://localhost:5700/api/categories | jq '.' 2>/dev/null || curl -s http://localhost:5700/api/categories
    
    echo -e "\n🚗 Trim配置测试:"
    curl -s "http://localhost:5700/api/get_trims?model=Puma" | jq '.[0:1]' 2>/dev/null || curl -s "http://localhost:5700/api/get_trims?model=Puma" | head -5
    
    echo -e "\n${GREEN}✅ 完整测试完成！${NC}"
fi

echo -e "\n祝您使用愉快！🚀"
